package ti.me.seek2chat.adapters

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ti.me.seek2chat.databinding.ItemContainerUserBinding
import ti.me.seek2chat.listeners.UserListener
import ti.me.seek2chat.models.User

/**
 * UsersAdapter 是一个 RecyclerView 适配器，用于显示用户列表。
 * @param users 用户列表
 * @param userListener 用户点击监听器
 */
class UsersAdapter(private val users: List<User>, private val userListener: UserListener) :
    RecyclerView.Adapter<UsersAdapter.UserViewHolder>() {
    /**
     * UserViewHolder 是一个 ViewHolder，用于绑定用户数据到视图。
     * @param binding 视图绑定对象
     * @param userListener 用户点击监听器
     */
    class UserViewHolder(
        private val binding: ItemContainerUserBinding,
        private val userListener: UserListener
    ) :
        RecyclerView.ViewHolder(binding.root) {

        /**
         * 绑定用户数据到视图。
         * @param user 用户对象
         */
        fun setUserData(user: User) {
            binding.textName.text = user.name
            binding.textEmail.text = user.email
            binding.imageProfile.setImageBitmap(getUserImage(user.image))
            binding.root.setOnClickListener {
                userListener.onUserClicked(user)
            }
        }


        /**
         * 将 Base64 编码的字符串转换为 Bitmap。
         * @param encodedImage Base64 编码的字符串
         * @return 解码后的 Bitmap
         */
        private fun getUserImage(encodedImage: String): Bitmap {
            val bytes = Base64.decode(encodedImage, Base64.DEFAULT)
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val itemContainerUserBinding =
            ItemContainerUserBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return UserViewHolder(itemContainerUserBinding, userListener)
    }

    override fun getItemCount(): Int {
        return users.size
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.setUserData(users[position])
    }
}